<template>
  <div class="p-6">
    <h2 class="text-2xl font-bold mb-4">📚 个人博客列表</h2>

    <el-input
      v-model="searchKeyword"
      placeholder="搜索文章标题"
      clearable
      class="mb-4"
      @clear="handleSearch"
      @keyup.enter="handleSearch"
    />

    <el-card
      v-for="blog in blogs"
      :key="blog.id"
      class="mb-4 cursor-pointer"
      @click="goToDetail(blog.id)"
    >
      <h3 class="text-xl font-semibold">{{ blog.title }}</h3>
      <p class="mt-1 text-gray-700 line-clamp-2">{{ blog.summary }}</p>
      <p class="text-gray-500 text-sm">{{ formatDate(blog.createTime) }}</p>
    </el-card>

    <el-pagination
      v-if="pagination.total > 0"
      class="mt-6"
      background
      layout="prev, pager, next"
      :total="pagination.total"
      :page-size="pagination.pageSize"
      :current-page="pagination.currentPage"
      @current-change="handlePageChange"
      :disabled="loading"
    />

    <div class="button-wrapper">
      <el-button type="success" @click="goToAdmin">博客管理</el-button>
      <el-button type="primary" @click="goBack">返回</el-button>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from "vue";
import { useRouter } from "vue-router";
import { fetchBlogList } from "../api/blogList";

const router = useRouter();
const blogs = ref([]);
const searchKeyword = ref("");
const loading = ref(false);
const pagination = ref({
  currentPage: 1,
  pageSize: 3,
  total: 0,
});

const fetchBlogs = async () => {
  loading.value = true;
  try {
    const res = await fetchBlogList({
      keyword: searchKeyword.value,
      pageNum: pagination.value.currentPage, // ✅ 和接口字段一致
      pageSize: pagination.value.pageSize,
    });

    if (res.code === 200 && res.data) {
      blogs.value = res.data.list || [];
      pagination.value.total = res.data.total || 0;
    } else {
      blogs.value = [];
      pagination.value.total = 0;
    }
  } catch (err) {
    console.error("获取博客列表失败:", err);
  } finally {
    loading.value = false;
  }
};

const handleSearch = async () => {
  pagination.value.currentPage = 1;
  await fetchBlogs();
};

const handlePageChange = async (page) => {
  pagination.value.currentPage = page;
  await fetchBlogs();
};

const goToDetail = (id) => {
  router.push(`/api/detail/${id}`);
};
const goToAdmin = () => {
  router.push("/api/admin");
};
const goBack = () => {
  router.back();
};

const formatDate = (isoStr) => {
  if (!isoStr) return "";
  const d = new Date(isoStr);
  return d.toLocaleDateString() + " " + d.toLocaleTimeString();
};

onMounted(() => {
  fetchBlogs();
});
</script>

<style scoped>
.cursor-pointer {
  cursor: pointer;
}
.line-clamp-2 {
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}
.button-wrapper {
  display: flex;
  justify-content: flex-end;
  align-items: flex-end;
  margin-bottom: 20px;
}
</style>
